<?php
/**
* @package YaForms
* @copyright Авторские права (C) 2009 www.yar-it.com. Все права защищены.
* @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
* YaForms! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
* Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл copyright.php.
*/


defined( '_VALID_MOS' ) or die( '' );

if (!($acl->acl_check( 'administration', 'edit', 'users', $my->usertype, 'components', 'all' )
		| $acl->acl_check( 'administration', 'edit', 'users', $my->usertype, 'components', 'com_yaforms' ))) {
	mosRedirect( 'index2.php', _NOT_AUTH );
}

require( $mainframe->getPath( 'admin_html' ) );
require( $mainframe->getPath( 'class' ) );

$id = mosGetParam( $_REQUEST, 'id', 0 );
$cid = mosGetParam( $_REQUEST, 'cid', 0 );
$task = mosGetParam( $_REQUEST, 'task', 'menu' );

//загружаем библиотеки
mosCommonHTML::loadJquery();
mosCommonHTML::loadOverlib();

afLoadLib( 'loadassets' );
afLoadLib( 'adm' );
afLoadLang();
showErrRep();
afLoadBECSS();


switch ( $task ) {
   case 'showaf':
      showYaForms( $option );
      break;
   case 'rforms':
      showRForms( $option );
      break;
   case 'vrforms':
      showViewRForms( $option );
      break;
   case 'help':
      HTML_yaforms::showHelp( $option );
      break;
   case 'language':
      HTML_yaforms::showLanguage();
      break;
   case 'cssedit':
      HTML_yaforms::showCSS();
      break;
   case 'config':
      HTML_yaforms::showConfig();
      break;
   case 'update':
      HTML_yaforms::showUpdate();
      break;
   case 'info':
      HTML_yaforms::showYaFormsInfo();
      break;
   case 'publish':
      publishYaForms( $cid, 1, $option );
      break;
   case 'unpublish':
      publishYaForms( $cid, 0, $option );
      break;
   case 'new':
      editYaForms( 0, $option );
      break;
   case 'edit':
      editYaForms( $cid[0], $option );
      break;
   case 'editA':
      editYaForms( $id, $option );
      break;
   case 'copy':
      copyYaForms( $cid, $option );
      break;
   case 'remove':
      removeYaForms( $cid, $option );
      break;
   case 'removerf':
      removeRForms( $cid, $option );
      break;
   case 'apply':
      saveYaForms( $database, $option, 1 );
      break;
   case 'save':
      saveYaForms( $database, $option );
      break;
   case 'savelanguage':
      saveLanguage( $option );
      break;
   case 'saveconfig':
      saveConfig( $option );
      break;
   case 'savecssedit':
      saveCSS( $option );
      break;
   case 'applylanguage':
      saveLanguage( $option, 1 );
      break;
   case 'applyconfig':
      saveConfig( $option, 1 );
      break;
   case 'applycssedit':
      saveCSS( $option, 1 );
      break;
   case 'uploadcfg':
      afUploadAsterisks();
      break;
   case 'afresethits':
      afResetHits( $id, $option );
      break;
   case 'menulink':
      afSaveMenu();
      break;
   case 'go2menu':
      afGo2Menu();
      break;
   case 'go2menuitem':
      afGo2MenuItem();
      break;
   case 'saveorder':
      afSaveOrder( $cid );
      break;
   case 'orderup':
      afOrder( intval( $cid[0] ), -1, $option );
      break;
   case 'orderdown':
      afOrder( intval( $cid[0] ), 1, $option );
      break;
   case 'accesspublic':
      afAccessMenu( intval( $cid[0] ), 0, $option );
      break;
   case 'accessregistered':
      afAccessMenu( intval( $cid[0] ), 1, $option );
      break;
   case 'accessspecial':
      afAccessMenu( intval( $cid[0] ), 2, $option );
      break;
   case 'cancel':
      cancelYaForms( $option );
      break;
   case 'delrow':
      afDelRow( $id, $option );
      break;
   case "exprformscsv":
      afExportRFormsCSV( $option, $cid );
      break;
   case "exprformsxls":
      afExportRFormsXLS( $option, $cid );
      break;
   case 'menu':
      HTML_yaforms::showArtformsPanel();
      break;
   case 'cancellanguage':
   case 'cancelconfig':
   case 'cancelupdate':
   case 'cancelhelp':
   case 'cancelinfo':
   case 'cancelcssedit':
   case 'cancelrforms':
   default:
      $subtask = mosGetParam( $_REQUEST, 'subtask', '' );
      switch ( $subtask ) {
         case 'showaf':
            showYaForms( $option );
            break;
         case 'rforms':
            showRForms( $option );
            break;
         default:
            mosRedirect( 'index2.php?option=com_yaforms&task=menu' );
            break;
      }
      break;
}


function showYaForms( $option ) {

   global $database, $mainframe, $option, $mosConfig_list_limit;

   $limit      = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
   $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
   $search     = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
   $search     = $database->getEscaped( trim( strtolower( $search ) ) );

   if (get_magic_quotes_gpc()) {
      $search = stripslashes( $search );
   }
	
   if ($search) {
      $where = " WHERE a.titel LIKE '%$search%' OR a.text LIKE '%$search%'";
   } else {
      $where = "";
   }
   
   $database->setQuery( "SELECT count(*) FROM #__yaforms AS a $where" );
   $total = $database->loadResult();

   require_once( JPATH_BASE.'/administrator/components/com_yaforms/lib/af.lib.pagenav.php' );
   $pageNav = new mosPageNav( $total, $limitstart, $limit );

   $query = "SELECT a.*, u.name AS editor, g.name AS groupname"
	  . "\nFROM #__yaforms AS a"
	  . "\nLEFT JOIN #__users AS u ON u.id=a.checked_out"
	  . "\nLEFT JOIN #__groups AS g ON g.id = a.access"
	  . "\n$where ORDER BY ordering ASC";
   $database->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
   $rows = $database->loadObjectList();

   HTML_yaforms::showYaForms( $rows, $search, $pageNav, $option );

}


function saveYaForms( &$db, $option, $apply=0 ) {

        global $my, $option, $task, $mainframe, $database, $id, $mosConfig_offset;

        $nullDate = $database->getNullDate();
        $row = new mosyaforms( $database );

        afLoadLib( 'attfiles' );
	$_POST['allowattfiles']= afPostAtt2DB();
        
	$a_post_items = null;
	$itemcount = count($_POST['item_id']);
	for($i = 0; $i<$itemcount; $i++){
	
		if($database->getErrorNum()) {
		   return $database->getErrorMsg();
		}

		$a_post_items[] = array(item_id        => $_POST['item_id'][$i],
					form_id        => $_POST['id'],
					name           => trim($_POST['name'][$i]),
					type           => $_POST['type'][$i],
					required       => $_POST['required'][$i],
					validation     => $_POST['validation'][$i],
					values         => trim($_POST['values'][$i]),
					default_values => trim($_POST['default_values'][$i]),
					readonly       => $_POST['readonly'][$i],
					customcode     => trim($_POST['customcode'][$i]),
					layout         => trim($_POST['layout'][$i]),
					item_ordering  => $_POST['item_ordering'][$i]
                                       );
	}
	
	$row->titel = ampReplace( $row->titel );
	$row->text = str_replace( '<br>', '<br />', $row->text );
	$row->danktext 	= str_replace( '<br>', '<br />', $row->danktext );

	$row->created_by = $row->created_by ? $row->created_by : $my->id;

	if ($row->created && strlen(trim( $row->created )) <= 10) {
		$row->created .= ' 00:00:00';
	}
        $row->created = $row->created ? mosFormatDate( $row->created, '%Y-%m-%d %H:%M:%S', -$mosConfig_offset ) : date( 'Y-m-d H:i:s' );

	if (strlen(trim( $row->publish_up )) <= 10) {
		$row->publish_up .= ' 00:00:00';
 	}
	$row->publish_up = mosFormatDate( $row->publish_up, _CURRENT_SERVER_TIME_FORMAT, -$mosConfig_offset );

	if (trim( $row->publish_down ) == _NEVER || trim( $row->publish_down ) == '') {
		$row->publish_down = $nullDate;
	} else {
		if (strlen(trim( $row->publish_down )) <= 10) {
			$row->publish_down .= ' 00:00:00';
		}
		$row->publish_down = mosFormatDate( $row->publish_down, _CURRENT_SERVER_TIME_FORMAT, -$mosConfig_offset );
	}

        $query = "SELECT name"
		. "\n FROM #__users"
		. "\n WHERE id = " . (int) $row->created_by
		;
	$database->setQuery( $query );
	$row->author = $database->loadResult();

        $row->id = (int) $row->id;
        
        if (mosGetParam( $_POST, 'id' )) {
		$row->modified = date( 'Y-m-d H:i:s' );
		$row->modified_by = $my->id;

                $query = "SELECT name"
		. "\n FROM #__users"
		. "\n WHERE id = " . (int) $row->modified_by
		;
	        $database->setQuery( $query );
         	$row->modifier = $database->loadResult();

	}
	
	$params = mosGetParam( $_POST, 'params', '' );
	if (is_array( $params )) {
		$txt = array();
		foreach ( $params as $k=>$v) {
			if (get_magic_quotes_gpc()) {
				$v = stripslashes( $v );
			}
			$txt[] = "$k=$v";
		}
		$row->attribs = implode( "\n", $txt );
	}
	
	$obj_items = null;
	for($i = 0; $i<count($a_post_items); $i++){
		$obj_items[$i] = new mosyaforms_item ( $database );
		mosBindArrayToObject($a_post_items[$i], $obj_items[$i]);
	}
	
        if (!$row->check()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	
	// Bind Form Data
	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	// Save Form Data
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

        $row->checkin();
        
	foreach($obj_items as $item){

		if(mosGetParam( $_POST, 'id' ) == 0){
			$item->form_id = $row->id;
		}

		if($item->name == ''){
			if (!$item->delete()) {
				echo 'delete error';
				echo "<script> alert('".$item->getError()."'); window.history.go(-1); </script>\n";
				exit();
			}
		} else {
			if (!$item->store()) {
				echo 'store error';
				echo "<script> alert('".$item->getError()."'); window.history.go(-1); </script>\n";
				exit();
			}
		}
	}
	mosCache::cleanCache( 'com_yaforms' );
	
	$msg = YAF_FORM_FORMSAVED;
        if( $apply == 1 ){

           if( $id == '' ){
              $query = 'SELECT id FROM #__yaforms ORDER BY id DESC';
              $database->setQuery( $query );
              $getrow = $database->loadRow();
              $getid = $getrow[0];
           } else {
              $getid = $id;
           }
           
           mosRedirect( 'index2.php?option='.$option.'&amp;task=editA&id='.$getid, $msg );
        } else {
           mosRedirect( 'index2.php?option='.$option.'&amp;task=showaf', $msg  );
        }

}


function editYaForms( $cid, $option ) {

   global $my, $option, $task, $mainframe, $database;
   $row = new mosyaforms( $database );
   $row->load( $cid );
   $nullDate = $database->getNullDate();
   $formid = $row->id;
   
   
   if($row->isCheckedOut( $my->id )){
      mosRedirect( 'index2.php?option=com_yaforms&task=showaf', $row->titel.' is currently being edited by another administrator.' );
   }
	 if ($formid == '') {
	 
	 $items=0;
	 
	 }else{
	 
   $query = "SELECT *"
	   ."\n FROM #__yaforms_items"
	   ."\n WHERE form_id = $formid"
	   ."\n ORDER BY item_ordering ASC"
	   ;
   $database->setQuery( $query );
   $items = $database->loadObjectList();
   }
   
   $lists = array();
   $itlists = array();
   
   $formopt[] = mosHTML::makeOption( '0', YAF_FORM_TEXTMAIL );
   $formopt[] = mosHTML::makeOption( '1', YAF_FORM_HTMLMAIL );
   $lists['formopt'] = mosHTML::selectList( $formopt, 'html', 'class="text_area" size="1"', 'value', 'text', $row->html );

   $afeditorallow[] = mosHTML::makeOption( 'tinymce_light', 'JCE Light' );
   $afeditorallow[] = mosHTML::makeOption( 'tinymce_simple', 'JCE Simple' );
   $afeditorallow[] = mosHTML::makeOption( 'tinymce_full', 'JCE Full' );
   $afeditorallow[] = mosHTML::makeOption( 'fckeditor_def', 'FCK Editor - Default' );
   $afeditorallow[] = mosHTML::makeOption( 'fckeditor_o2003', 'FCK Editor - Office 2003' );
   $afeditorallow[] = mosHTML::makeOption( 'fckeditor_silver', 'FCK Editor - Silver' );
   //$afeditorallow[] = mosHTML::makeOption( 'htmlarea3_xtd', 'HtmlArea3 Xtd' );
   //$afeditorallow[] = mosHTML::makeOption( 'jce', 'JCE' );
   //$afeditorallow[] = mosHTML::makeOption( 'jeditor', 'JEditor' );
   //$afeditorallow[] = mosHTML::makeOption( 'tmedit', 'TMEdit' );
   //$afeditorallow[] = mosHTML::makeOption( 'wysiwygpro', 'WYSIWYG Pro' );
   //$afeditorallow[] = mosHTML::makeOption( 'xinha', 'Xinha' );
   //$afeditorallow[] = mosHTML::makeOption( 'xstandard', 'X Standard' );
   $lists['afeditor'] = mosHTML::selectList( $afeditorallow, 'afeditor', 'class="text_area" size="1"', 'value', 'text', $row->afeditor );

   $seccodeallow[] = mosHTML::makeOption( '0', YAF_FORM_NONE );
   $seccodeallow[] = mosHTML::makeOption( '1', YAF_MULTI_YES);
   $lists['seccodeallow'] = mosHTML::selectList( $seccodeallow, 'seccode', 'class="text_area" size="1"', 'value', 'text', $row->seccode );
   
   $emailfieldallow[] = mosHTML::makeOption( '0', YAF_MULTI_NO );
   $emailfieldallow[] = mosHTML::makeOption( '1', YAF_MULTI_YES );
   $lists['emailfieldallow'] = mosHTML::selectList( $emailfieldallow, 'emailfield', 'class="text_area" size="1"', 'value', 'text', $row->emailfield );

   $formattallow[] = mosHTML::makeOption( '0', YAF_FORM_WITHOUTATTF );
   $formattallow[] = mosHTML::makeOption( '1', YAF_FORM_ATTFSIMPLE );
   $formattallow[] = mosHTML::makeOption( '2', YAF_FORM_ATTFGMAIL );
   $formattallow[] = mosHTML::makeOption( '3', YAF_FORM_ATTFSMMU );
   $lists['formattallow'] = mosHTML::selectList( $formattallow, 'allowatt', 'class="text_area" size="1"', 'value', 'text', $row->allowatt);

   $itlists['newslettersel'][] = mosHTML::makeOption( '0', YAF_FORM_NONE );
   $itlists['newslettersel'][] = mosHTML::makeOption( 'letterman', 'Letterman' );

   $itlists['a_types'][] = mosHTML::makeOption( '1',  YAF_FORM_INPUT );
   $itlists['a_types'][] = mosHTML::makeOption( '2',  YAF_FORM_TEXTAREA );
   $itlists['a_types'][] = mosHTML::makeOption( '3',  YAF_FORM_LIST );
   $itlists['a_types'][] = mosHTML::makeOption( '4',  YAF_FORM_CHECKBOX );
   $itlists['a_types'][] = mosHTML::makeOption( '5',  YAF_FORM_DROPDS );
   $itlists['a_types'][] = mosHTML::makeOption( '6',  YAF_FORM_DROPDM );
   $itlists['a_types'][] = mosHTML::makeOption( '7',  YAF_FORM_DATE );
   $itlists['a_types'][] = mosHTML::makeOption( '8',  YAF_FORM_HTMLTEXT );
   $itlists['a_types'][] = mosHTML::makeOption( '9',  YAF_FORM_TEXTAREAPLAIN );
   $itlists['a_types'][] = mosHTML::makeOption( '10', YAF_FORM_HIDDENINPUT );
   $itlists['a_types'][] = mosHTML::makeOption( '11', YAF_FORM_PASSWORD );
   $itlists['a_types'][] = mosHTML::makeOption( '12', YAF_FORM_PASSWORD2 );
   
   $itlists['a_requ'][] = mosHTML::makeOption( '1', YAF_FORM_OPTIONAL );
   $itlists['a_requ'][] = mosHTML::makeOption( '2', YAF_FORM_MANDATORY );

   $itlists['a_valid'][] = mosHTML::makeOption( '0', YAF_FORM_NONE );
   $itlists['a_valid'][] = mosHTML::makeOption( '1', YAF_FORM_EMAIL );
   $itlists['a_valid'][] = mosHTML::makeOption( '2', YAF_FORM_NUMBER );
   $itlists['a_valid'][] = mosHTML::makeOption( '3', YAF_FORM_TEXT );
   $itlists['a_valid'][] = mosHTML::makeOption( '4', YAF_FORM_TEXTNUMBER );
   $itlists['a_valid'][] = mosHTML::makeOption( '5', YAF_FORM_DECIMAL );
   $itlists['a_valid'][] = mosHTML::makeOption( '6', YAF_FORM_DATE );
   $itlists['a_valid'][] = mosHTML::makeOption( '7', YAF_FORM_ZIPCODE );
   $itlists['a_valid'][] = mosHTML::makeOption( '8', YAF_FORM_IP );
   $itlists['a_valid'][] = mosHTML::makeOption( '9', YAF_FORM_URL );
   $itlists['a_valid'][] = mosHTML::makeOption( '10', YAF_FORM_CREDITCARD );
   $itlists['a_valid'][] = mosHTML::makeOption( '11', YAF_FORM_CUSTOM.' 1' );
   $itlists['a_valid'][] = mosHTML::makeOption( '12', YAF_FORM_CUSTOM.' 2' );
   $itlists['a_valid'][] = mosHTML::makeOption( '13', YAF_FORM_CUSTOM.' 3' );
   $itlists['a_valid'][] = mosHTML::makeOption( '14', YAF_FORM_CUSTOM.' 4' );
   $itlists['a_valid'][] = mosHTML::makeOption( '15', YAF_FORM_CUSTOM.' 5' );

   $itlists['a_ronly'][] = mosHTML::makeOption( '0', YAF_MULTI_NO );
   $itlists['a_ronly'][] = mosHTML::makeOption( '1', YAF_MULTI_YES );

   $lists['emailfieldallow'] = mosHTML::selectList( $emailfieldallow, 'emailfield', 'class="text_area" size="1"', 'value', 'text', $row->emailfield );
   $itlists['addFieldx'][] = mosHTML::makeOption( 'n', YAF_FORM_NONE );
   for ($i=1; $i<31; $i++) {
      $itlists['addFieldx'][] = mosHTML::makeOption( $i, $i );
   }
   
   $row->created = mosFormatDate( $row->created, _CURRENT_SERVER_TIME_FORMAT );
   $row->modified = $row->modified == $nullDate ? '' : mosFormatDate( $row->modified, _CURRENT_SERVER_TIME_FORMAT );
   $row->publish_up = mosFormatDate( $row->publish_up, _CURRENT_SERVER_TIME_FORMAT );

   if (trim( $row->publish_down ) == $nullDate || trim( $row->publish_down ) == '' || trim( $row->publish_down ) == '-' ) {
      $row->publish_down = _NEVER;
   }
   $row->publish_down = mosFormatDate( $row->publish_down, _CURRENT_SERVER_TIME_FORMAT );

   $query = "SELECT name"
   . "\n FROM #__users"
   . "\n WHERE id = " . (int) $row->created_by
   ;
   $database->setQuery( $query );
   $row->author = $database->loadResult();

   if ( $row->created_by == $row->modified_by ) {
      $row->modifier = $row->author;
   } else {
      $query = "SELECT name"
      . "\n FROM #__users"
      . "\n WHERE id = " . (int) $row->modified_by
      ;
      $database->setQuery( $query );
      $row->modifier = $database->loadResult();
   }
   
   $active = ( intval( $row->created_by ) ? intval( $row->created_by ) : $my->id );
   $lists['created_by'] = mosAdminMenus::UserSelect( 'created_by', $active );
   $lists['access'] = mosAdminMenus::Access( $row );

   $query = "SELECT ordering AS value, titel AS text"
	. "\n FROM #__yaforms"
	. "\n ORDER BY ordering"
	;
   $lists['ordering'] = mosAdminMenus::SpecificOrdering( $row, $cid, $query, 1 );

   $params = new mosParameters( $row->attribs, $mainframe->getPath( 'com_xml', 'com_yaforms' ), 'component' );
   
   if($cid){
      $row->checkout( $my->id );
   }
   
   HTML_yaforms::editYaForms( $row, $option, $formid, $items, $lists, $itlists, $params );

}


function showRForms( $option ) {

	global $database, $mainframe, $mosConfig_list_limit;

        $limit      = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
        $limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
        $search     = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
        $search     = $database->getEscaped( trim( strtolower( $search ) ) );

        if (get_magic_quotes_gpc()) {
           $search = stripslashes( $search );
        }

        if ($search) {
           $where = " WHERE a.item_data LIKE '%$search%'";
        } else {
           $where = "";
        }

        $database->setQuery( "SELECT count(*) FROM #__yaforms_inbox AS a $where" );
        $total = $database->loadResult();

        require_once( JPATH_BASE.'/administrator/components/com_yaforms/lib/af.lib.pagenav.php' );
        $pageNav = new mosPageNav( $total, $limitstart, $limit );

        $query = "SELECT *"
        . "\n FROM #__yaforms_inbox"
        . "\n ORDER BY id DESC"
        ;
        $database->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
        $rows = $database->loadObjectList();

	HTML_yaforms::showRForms( $rows, $search, $pageNav, $option );
	
}


function showViewRForms( $option ) {

        global $database;

        $id = mosGetParam( $_GET, 'id' );

	$database->setQuery( "SELECT * FROM #__yaforms_inbox WHERE id = $id ORDER BY id DESC" );
	$rows = $database->loadObjectList();

	HTML_yaforms::showViewRForms( $rows, $option );
}


function saveLanguage( $option, $apply=0 ) {

           $fname = mosGetParam( $_POST, 'fname' );
           $fcontent = $_POST['fcontent'];
           $fcontent = stripslashes($fcontent);

	   $enable_write = mosGetParam( $_POST, 'enable_write', 0 );
	   $oldperms = fileperms($fname);

	   if ( $enable_write ) {
		@chmod( $fname, $oldperms | 0222);
	   }

           clearstatcache();

	   if ( $fp = @fopen($fname, 'w') ) {
		fputs($fp, $fcontent, strlen($fcontent));
		fclose($fp);
		if ($enable_write) {
			@chmod($fname, $oldperms);
		} else {
                        if( mosGetParam( $_POST, 'disable_write', 0 )){
                           @chmod($fname, $oldperms & 0777555);
                        }
		}

		$msg = YAF_MULTI_FSAVEDSUCCESS;

           } else {

		if ($enable_write) {
			@chmod( $fname, $oldperms );
		}

		$msg = YAF_MULTI_WRITENOTALLOWERROR;
	   }

           if( $apply == 1 ){
              mosRedirect( 'index2.php?option='.$option.'&amp;task=language', $msg  );
           } else {
              mosRedirect( 'index2.php?option='.$option.'&amp;task=menu', $msg );
           }
}


function saveCSS( $option, $apply=0 ) {

           $fname = mosGetParam( $_POST, 'fname' );
           $fcontent = $_POST['fcontent'];
           $fcontent = stripslashes($fcontent);

	   $enable_write = intval( mosGetParam( $_POST, 'enable_write', 0 ) );
	   $oldperms = fileperms($fname);
	   if ( $enable_write ) {
		@chmod( $fname, $oldperms | 0222);
	   }

	   if ( $fp = fopen($fname, 'w') ) {
		fputs($fp, $fcontent, strlen($fcontent));
		fclose($fp);
		if ($enable_write) {
			@chmod($fname, $oldperms);
		} else {
			if ( mosGetParam( $_POST, 'disable_write', 0 ) ){
                           @chmod($fname, $oldperms & 0777555);
                        }
		}

                $msg = YAF_MULTI_FSAVEDSUCCESS;
                if( $apply == 1 ){
                   mosRedirect( 'index2.php?option='.$option.'&amp;task=cssedit', $msg  );
                } else {
                   mosRedirect( 'index2.php?option='.$option.'&amp;task=menu', $msg );
                }

           } else {
		if ($enable_write) {
			@chmod( $fname, $oldperms );
		}
                $msg = YAF_MULTI_WRITENOTALLOWERROR;
                if( $apply == 1 ){
                   mosRedirect( 'index2.php?option='.$option.'&amp;task=language', $msg );
                } else {
                   mosRedirect( 'index2.php?option='.$option.'&amp;task=menu', $msg  );
                }
	   }

}


function saveConfig( $option, $apply=0 ) {

   $afcfg_att_path        = mosGetParam( $_POST, 'afcfg_att_path', '/images/yaforms/attachedfiles/' );
   $afcfg_bkup_path       = mosGetParam( $_POST, 'afcfg_bkup_path', '/administrator/components/com_yaforms/backups/' );
   $afcfg_attimagew       = mosGetParam( $_POST, 'afcfg_attimagew', null );
   $afcfg_attimageh       = mosGetParam( $_POST, 'afcfg_attimageh', null );
   $afcfg_attfilesave     = mosGetParam( $_POST, 'afcfg_attfilesave', null );
   $afcfg_loadfrontcss    = mosGetParam( $_POST, 'afcfg_loadfrontcss', null );
   $afcfg_showfrontfooter = mosGetParam( $_POST, 'afcfg_showfrontfooter', null );
   $afcfg_allowajax       = mosGetParam( $_POST, 'afcfg_allowajax', null );
   $afcfg_dbsaveforms     = mosGetParam( $_POST, 'afcfg_dbsaveforms', null );
   $afcfg_allowerr_rep    = mosGetParam( $_POST, 'afcfg_allowerr_rep', null );
   $afcfg_beitemsinterfase = mosGetParam( $_POST, 'afcfg_beitemsinterfase', 'ajax' );
   $afcfg_showferforms = mosGetParam( $_POST, 'afcfg_showferforms', null );
   $afcfg_showattinvferforms = mosGetParam( $_POST, 'afcfg_showattinvferforms', null );
   $afcfg_usebehelper     = mosGetParam( $_POST, 'afcfg_usebehelper', '0' );
   $afcfg_fieldsdefaultlayout = mosGetParam( $_POST, 'afcfg_fieldsdefaultlayout', null, _MOS_ALLOWRAW );
   $afcfg_asteriskimg     = mosGetParam( $_POST, 'afcfg_asteriskimg', null );
   $afcfg_valide_zipcode  = mosGetParam( $_POST, 'afcfg_valide_zipcode', null );
   $afcfg_valide_custom1  = mosGetParam( $_POST, 'afcfg_valide_custom1', null );
   $afcfg_valide_custom2  = mosGetParam( $_POST, 'afcfg_valide_custom2', null );
   $afcfg_valide_custom3  = mosGetParam( $_POST, 'afcfg_valide_custom3', null );
   $afcfg_valide_custom4  = mosGetParam( $_POST, 'afcfg_valide_custom4', null );
   $afcfg_valide_custom5  = mosGetParam( $_POST, 'afcfg_valide_custom5', null );
   $afcfg_valide_custom1_legend  = mosGetParam( $_POST, 'afcfg_valide_custom1_legend', null );
   $afcfg_valide_custom2_legend  = mosGetParam( $_POST, 'afcfg_valide_custom2_legend', null );
   $afcfg_valide_custom3_legend  = mosGetParam( $_POST, 'afcfg_valide_custom3_legend', null );
   $afcfg_valide_custom4_legend  = mosGetParam( $_POST, 'afcfg_valide_custom4_legend', null );
   $afcfg_valide_custom5_legend  = mosGetParam( $_POST, 'afcfg_valide_custom5_legend', null );
   $afcfg_captcha_mode    = mosGetParam( $_POST, 'afcfg_captcha_mode', null );
   $afcfg_captcha_length  = mosGetParam( $_POST, 'afcfg_captcha_length', null );
   $afcfg_captcha_recapt_theme = mosGetParam( $_POST, 'afcfg_captcha_recapt_theme', null );
   $afcfg_captcha_recapt_tabindex = mosGetParam( $_POST, 'afcfg_captcha_recapt_tabindex', null );
   $afcfg_captcha_recapt_publickey = mosGetParam( $_POST, 'afcfg_captcha_recapt_publickey', null );
   $afcfg_captcha_recapt_privatekey = mosGetParam( $_POST, 'afcfg_captcha_recapt_privatekey', null );

   global $database, $option;

   $afcfg_fieldsdefaultlayout = str_replace('\"','"',$afcfg_fieldsdefaultlayout);
   $afcfg_fieldsdefaultlayout = urlencode( $afcfg_fieldsdefaultlayout );

   $params[]= 'rootfronttitle='.mosGetParam( $_POST, 'rootfronttitle', null );
   $params[]= 'fronttext='.urlencode( mosGetParam( $_POST, 'fronttext', null, _MOS_ALLOWRAW ) );
   $compid  = mosGetParam( $_POST, 'compid', null );
   $params  = implode( "\n", $params );

   $row = new mosComponent( $database );
   $row->load( $compid );
   $row->params = $params;

   if (!$row->check()) {
   echo "<script type=\"text/javascript\"> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
   exit();
   }
   if (!$row->store()) {
   echo "<script type=\"text/javascript\"> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
   exit();
   }

   $fname = JPATH_BASE.'/administrator/components/com_yaforms/config.yaforms.php';
   $enable_write = intval( $_POST['enable_write'], 0 );
   $oldperms = fileperms($fname);
   if ( $enable_write ) {
      @chmod( $fname, $oldperms | 0222);
   }

   $config = "<?php\n";
   $config .= "\$afcfg_att_path                  = '$afcfg_att_path';\n";
   $config .= "\$afcfg_bkup_path                 = '$afcfg_bkup_path';\n";
   $config .= "\$afcfg_attimagew                 = '$afcfg_attimagew';\n";
   $config .= "\$afcfg_attimageh                 = '$afcfg_attimageh';\n";
   $config .= "\$afcfg_attfilesave               = '$afcfg_attfilesave';\n";
   $config .= "\$afcfg_loadfrontcss              = '$afcfg_loadfrontcss';\n";
   $config .= "\$afcfg_showfrontfooter           = '$afcfg_showfrontfooter';\n";
   $config .= "\$afcfg_allowajax                 = '$afcfg_allowajax';\n";
   $config .= "\$afcfg_dbsaveforms               = '$afcfg_dbsaveforms';\n";
   $config .= "\$afcfg_allowerr_rep              = '$afcfg_allowerr_rep';\n";
   $config .= "\$afcfg_beitemsinterfase          = '$afcfg_beitemsinterfase';\n";
   $config .= "\$afcfg_usebehelper               = '$afcfg_usebehelper';\n";
   $config .= "\$afcfg_fieldsdefaultlayout       = '$afcfg_fieldsdefaultlayout';\n";
   $config .= "\$afcfg_asteriskimg               = '$afcfg_asteriskimg';\n";
   $config .= "\$afcfg_showferforms              = '$afcfg_showferforms';\n";
   $config .= "\$afcfg_showattinvferforms        = '$afcfg_showattinvferforms';\n";
   $config .= "\$afcfg_valide_zipcode            = '$afcfg_valide_zipcode';\n";
   $config .= "\$afcfg_valide_custom1            = '$afcfg_valide_custom1';\n";
   $config .= "\$afcfg_valide_custom1_legend     = '$afcfg_valide_custom1_legend';\n";
   $config .= "\$afcfg_valide_custom2            = '$afcfg_valide_custom2';\n";
   $config .= "\$afcfg_valide_custom2_legend     = '$afcfg_valide_custom2_legend';\n";
   $config .= "\$afcfg_valide_custom3            = '$afcfg_valide_custom3';\n";
   $config .= "\$afcfg_valide_custom3_legend     = '$afcfg_valide_custom3_legend';\n";
   $config .= "\$afcfg_valide_custom4            = '$afcfg_valide_custom4';\n";
   $config .= "\$afcfg_valide_custom4_legend     = '$afcfg_valide_custom4_legend';\n";
   $config .= "\$afcfg_valide_custom5            = '$afcfg_valide_custom5';\n";
   $config .= "\$afcfg_valide_custom5_legend     = '$afcfg_valide_custom5_legend';\n";
   $config .= "\$afcfg_captcha_mode              = '$afcfg_captcha_mode';\n";
   $config .= "\$afcfg_captcha_length            = '$afcfg_captcha_length';\n";
   $config .= "\$afcfg_captcha_recapt_theme      = '$afcfg_captcha_recapt_theme';\n";
   $config .= "\$afcfg_captcha_recapt_tabindex   = '$afcfg_captcha_recapt_tabindex';\n";
   $config .= "\$afcfg_captcha_recapt_publickey  = '$afcfg_captcha_recapt_publickey';\n";
   $config .= "\$afcfg_captcha_recapt_privatekey = '$afcfg_captcha_recapt_privatekey';\n";
   $config .= "?".">";

   if ( $fp = fopen($fname, 'w') ) {
      fputs($fp, $config, strlen($config));
      fclose($fp);
      if ($enable_write) {

         @chmod($fname, $oldperms);

      } else {

         if (mosGetParam($_POST,'disable_write', 0 )){
            @chmod($fname, $oldperms & 0777555);
         }

      }
      $msg = YAF_CFG_CONFIGSAVED;
      if( $apply == 1 ){
         mosRedirect( 'index2.php?option='.$option.'&amp;task=config', $msg );
      } else {
         mosRedirect( 'index2.php?option='.$option.'&amp;task=menu', $msg );
      }

   } else {

      if ($enable_write) {
	 @chmod( $fname, $oldperms );
      }
      $msg = YAF_CFG_FILEERROR;
      if( $apply == 1 ){
         mosRedirect( 'index2.php?option='.$option.'&amp;task=language', $msg );
      } else {
         mosRedirect( 'index2.php?option='.$option.'&amp;task=menu', $msg );
      }

   }

}


?>